<template>
  <div class="type-container">
    <div class="person-container">
      <LeftMenu />
      <div class="type-content">
        <el-card>
          <ManagementTitle>
            <template #title>
              户型管理 - {{ buildingName }} ({{ plotName }})
              <el-button size="small" @click="goBack" style="margin-left: 16px;">返回楼栋列表</el-button>
            </template>
          </ManagementTitle>
          
          <!-- 操作按钮区域 -->
          <div class="type-header">
            <el-button type="primary" @click="handleAdd">
              <el-icon><Plus /></el-icon>
              新增户型
            </el-button>
            <el-button type="danger" @click="handleBatchDelete" :disabled="selectedIds.length === 0">
              <el-icon><Delete /></el-icon>
              批量删除
            </el-button>
            <el-button type="info" @click="handleExport">
              <el-icon><Download /></el-icon>
              导出数据
            </el-button>
          </div>
          
          <!-- 搜索区域 -->
          <div class="type-search">
            <el-input
              v-model="searchForm.name"
              placeholder="请输入户型名称"
              style="width: 200px; margin-right: 12px"
              clearable
            />
            <el-select
              v-model="searchForm.roomNum"
              placeholder="选择室数"
              style="width: 120px; margin-right: 12px"
              clearable
            >
              <el-option label="1室" :value="1" />
              <el-option label="2室" :value="2" />
              <el-option label="3室" :value="3" />
              <el-option label="4室" :value="4" />
              <el-option label="5室" :value="5" />
            </el-select>
            <el-input
              v-model="searchForm.towards"
              placeholder="请输入朝向"
              style="width: 150px; margin-right: 12px"
              clearable
            />
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button @click="handleReset">重置</el-button>
          </div>
          
          <!-- 户型表格 -->
          <el-table 
            :data="typeList" 
            border 
            style="width: 100%; margin-top: 16px;" 
            v-loading="loading"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column prop="name" label="户型名称" align="center" min-width="150" show-overflow-tooltip />
            <el-table-column label="户型配置" align="center" width="150">
              <template #default="{ row }">
                {{ row.roomNum }}室{{ row.hallNum }}厅{{ row.kitchenNum }}厨{{ row.bathroomNum }}卫
              </template>
            </el-table-column>
            <el-table-column prop="houseArea" label="房屋面积" align="center" width="120">
              <template #default="{ row }">
                {{ row.houseArea }}㎡
              </template>
            </el-table-column>
            <el-table-column prop="towards" label="朝向" align="center" width="100" />
            <el-table-column label="状态" align="center" width="100">
              <template #default="{ row }">
                <el-tag :type="row.delFlag === 0 ? 'success' : 'danger'">
                  {{ row.delFlag === 0 ? '正常' : '已删除' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="200" fixed="right">
              <template #default="{ row }">
                <el-button size="small" type="primary" @click="handleViewDetails(row)">详情</el-button>
                <el-button size="small" @click="handleEdit(row)" :disabled="row.delFlag === 1">编辑</el-button>
                <el-button size="small" type="danger" @click="handleDelete(row)" :disabled="row.delFlag === 1">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          
          <!-- 分页 -->
          <div class="table-pagination">
            <el-pagination
              background
              layout="total, prev, pager, next"
              :total="total"
              :page-size="pageSize"
              :current-page="currentPage"
              @current-change="handleCurrentChange"
            />
          </div>
        </el-card>
      </div>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="800px"
      :before-close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="120px"
        label-position="right"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="户型名称" prop="name">
              <el-input v-model="formData.name" placeholder="请输入户型名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="房屋面积" prop="houseArea">
              <el-input v-model="formData.houseArea" placeholder="如：120" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="室数" prop="roomNum">
              <el-input-number
                v-model="formData.roomNum"
                :min="1"
                :max="10"
                placeholder="室数"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="厅数" prop="hallNum">
              <el-input-number
                v-model="formData.hallNum"
                :min="0"
                :max="5"
                placeholder="厅数"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="厨房数" prop="kitchenNum">
              <el-input-number
                v-model="formData.kitchenNum"
                :min="0"
                :max="3"
                placeholder="厨房数"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="卫生间数" prop="bathroomNum">
              <el-input-number
                v-model="formData.bathroomNum"
                :min="0"
                :max="5"
                placeholder="卫生间数"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="朝向" prop="towards">
              <el-select v-model="formData.towards" placeholder="请选择朝向" style="width: 100%">
                <el-option label="东" value="东" />
                <el-option label="南" value="南" />
                <el-option label="西" value="西" />
                <el-option label="北" value="北" />
                <el-option label="东南" value="东南" />
                <el-option label="东北" value="东北" />
                <el-option label="西南" value="西南" />
                <el-option label="西北" value="西北" />
                <el-option label="南北" value="南北" />
                <el-option label="东西" value="东西" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleDialogClose">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
            {{ isEdit ? '更新' : '保存' }}
          </el-button>
        </span>
      </template>
    </el-dialog>


  </div>
</template>

<script setup lang="ts">
import LeftMenu from "@/user/LeftMenu.vue";
import { ref, reactive, onMounted, computed } from "vue";
import ManagementTitle from "@/components/ManagementTitle.vue";
import { ElMessage, ElMessageBox, ElForm } from 'element-plus';
import { Plus, Delete, Download } from '@element-plus/icons-vue';
import axios from 'axios';

// 响应式数据
const loading = ref(false);
const typeList = ref([]);
const total = ref(0);
const currentPage = ref(1);
const pageSize = 10;
const selectedIds = ref<any[]>([]);

// URL参数
const urlParams = new URLSearchParams(window.location.search);
const buildingId = ref(urlParams.get('buildingId'));
const buildingName = ref(decodeURIComponent(urlParams.get('buildingName') || ''));
const plotName = ref(decodeURIComponent(urlParams.get('plotName') || ''));

// 搜索表单
const searchForm = reactive({
  name: '',
  roomNum: null,
  towards: ''
});

// 对话框相关
const dialogVisible = ref(false);
const submitLoading = ref(false);
const isEdit = ref(false);
const formRef = ref<InstanceType<typeof ElForm>>();

// 表单数据
const formData = reactive({
  id: null,
  name: '',
  buildingId: null,
  roomNum: 1,
  hallNum: 1,
  kitchenNum: 1,
  bathroomNum: 1,
  houseArea: '',
  towards: ''
});

// 表单验证规则
const formRules = {
  name: [
    { required: true, message: '请输入户型名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  roomNum: [
    { required: true, message: '请输入室数', trigger: 'blur' }
  ],
  hallNum: [
    { required: true, message: '请输入厅数', trigger: 'blur' }
  ],
  kitchenNum: [
    { required: true, message: '请输入厨房数', trigger: 'blur' }
  ],
  bathroomNum: [
    { required: true, message: '请输入卫生间数', trigger: 'blur' }
  ],
  houseArea: [
    { required: true, message: '请输入房屋面积', trigger: 'blur' }
  ],
  towards: [
    { required: true, message: '请选择朝向', trigger: 'change' }
  ]
};

// 计算属性
const dialogTitle = computed(() => {
  return isEdit.value ? '编辑户型' : '新增户型';
});



const resetForm = () => {
  Object.assign(formData, {
    id: null,
    name: '',
    buildingId: null,
    roomNum: 1,
    hallNum: 1,
    kitchenNum: 1,
    bathroomNum: 1,
    houseArea: '',
    towards: ''
  });
  formRef.value?.clearValidate();
};

// API调用函数
const getTypeList = async () => {
  if (!buildingId.value) {
    ElMessage.error('缺少楼栋ID参数');
    return;
  }

  loading.value = true;
  try {
    console.log('请求参数:', { buildingId: buildingId.value });
    console.log('请求URL:', `/rental/areaplottype/getAllType/${buildingId.value}`);

    const response = await axios.get(`/rental/areaplottype/getAllType/${buildingId.value}`, {
      timeout: 10000,
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
      }
    });

    console.log('响应数据:', response.data);

    // 检查是否返回了HTML页面（代理失败）
    if (typeof response.data === 'string' && response.data.includes('<!DOCTYPE html>')) {
      console.error('代理失败，尝试直接调用后端API');
      // 尝试直接调用后端API
      const directResponse = await axios.get(`http://127.0.0.1:8081/rental/areaplottype/getAllType/${buildingId.value}`, {
        timeout: 10000,
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json'
        }
      });

      console.log('直接调用响应:', directResponse.data);

      if (directResponse.data.code === 0) {
        let list = directResponse.data.data || [];

        // 前端过滤（因为后端接口不支持搜索参数）
        if (searchForm.name && searchForm.name.trim()) {
          list = list.filter((item: any) =>
            item.name && item.name.toLowerCase().includes(searchForm.name.toLowerCase())
          );
        }
        if (searchForm.roomNum) {
          list = list.filter((item: any) => item.roomNum === searchForm.roomNum);
        }
        if (searchForm.towards && searchForm.towards.trim()) {
          list = list.filter((item: any) =>
            item.towards && item.towards.includes(searchForm.towards)
          );
        }

        typeList.value = list;
        total.value = list.length;
        ElMessage.success(`成功获取 ${list.length} 条户型数据`);
      } else {
        ElMessage.error(directResponse.data.msg || '获取户型列表失败');
      }
    } else if (response.data.code === 0) {
      let list = response.data.data || [];

      // 前端过滤（因为后端接口不支持搜索参数）
      if (searchForm.name && searchForm.name.trim()) {
        list = list.filter((item: any) =>
          item.name && item.name.toLowerCase().includes(searchForm.name.toLowerCase())
        );
      }
      if (searchForm.roomNum) {
        list = list.filter((item: any) => item.roomNum === searchForm.roomNum);
      }
      if (searchForm.towards && searchForm.towards.trim()) {
        list = list.filter((item: any) =>
          item.towards && item.towards.includes(searchForm.towards)
        );
      }

      typeList.value = list;
      total.value = list.length;
      ElMessage.success(`成功获取 ${list.length} 条户型数据`);
    } else {
      ElMessage.error(response.data.msg || '获取户型列表失败');
    }
  } catch (error) {
    console.error('获取户型列表失败:', error);
    ElMessage.error('获取户型列表失败，请检查网络连接');
  } finally {
    loading.value = false;
  }
};

// 保存户型
const saveType = async (data: any) => {
  try {
    const response = await axios.post('/rental/areaplottype', data);
    if (response.data.code === 0) {
      ElMessage.success('户型新增成功');
      return true;
    } else {
      ElMessage.error(response.data.msg || '新增失败');
      return false;
    }
  } catch (error) {
    console.error('新增户型失败:', error);
    ElMessage.error('新增失败，请检查网络连接');
    return false;
  }
};

// 更新户型
const updateType = async (data: any) => {
  try {
    const response = await axios.put('/rental/areaplottype', data);
    if (response.data.code === 0) {
      ElMessage.success('户型更新成功');
      return true;
    } else {
      ElMessage.error(response.data.msg || '更新失败');
      return false;
    }
  } catch (error) {
    console.error('更新户型失败:', error);
    ElMessage.error('更新失败，请检查网络连接');
    return false;
  }
};

// 删除户型
const deleteType = async (id: number) => {
  try {
    const response = await axios.delete('/rental/areaplottype/logicDelete', { data: [id] });
    if (response.data.code === 0) {
      ElMessage.success('户型删除成功');
      return true;
    } else {
      ElMessage.error(response.data.msg || '删除失败');
      return false;
    }
  } catch (error) {
    console.error('删除户型失败:', error);
    ElMessage.error('删除失败，请检查网络连接');
    return false;
  }
};

// 批量删除户型
const batchDeleteTypes = async (ids: number[]) => {
  try {
    const response = await axios.delete('/rental/areaplottype/logicDelete', { data: ids });
    if (response.data.code === 0) {
      ElMessage.success(`批量删除成功，共删除 ${ids.length} 个户型`);
      return true;
    } else {
      ElMessage.error(response.data.msg || '批量删除失败');
      return false;
    }
  } catch (error) {
    console.error('批量删除失败:', error);
    ElMessage.error('批量删除失败，请检查网络连接');
    return false;
  }
};

// 事件处理函数
const goBack = () => {
  window.close();
};

const handleSearch = () => {
  currentPage.value = 1;
  getTypeList();
};

const handleReset = () => {
  searchForm.name = '';
  searchForm.roomNum = null;
  searchForm.towards = '';
  currentPage.value = 1;
  getTypeList();
};

const handleCurrentChange = (page: number) => {
  currentPage.value = page;
  getTypeList();
};

const handleSelectionChange = (selection: any[]) => {
  selectedIds.value = selection.map(item => item.id);
};

const handleAdd = () => {
  isEdit.value = false;
  resetForm();
  dialogVisible.value = true;
};

const handleEdit = (row: any) => {
  isEdit.value = true;
  Object.assign(formData, {
    id: row.id,
    name: row.name,
    buildingId: row.buildingId,
    roomNum: row.roomNum,
    hallNum: row.hallNum,
    kitchenNum: row.kitchenNum,
    bathroomNum: row.bathroomNum,
    houseArea: row.houseArea,
    towards: row.towards
  });
  dialogVisible.value = true;
};

const handleDelete = async (row: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除户型"${row.name}"吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );

    const success = await deleteType(row.id);
    if (success) {
      getTypeList();
    }
  } catch {
    ElMessage.info('已取消删除');
  }
};

const handleBatchDelete = async () => {
  if (selectedIds.value.length === 0) {
    ElMessage.warning('请选择要删除的户型');
    return;
  }

  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedIds.value.length} 个户型吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );

    const success = await batchDeleteTypes(selectedIds.value);
    if (success) {
      selectedIds.value = [];
      getTypeList();
    }
  } catch {
    ElMessage.info('已取消删除');
  }
};

const handleExport = () => {
  window.open('/rental/areaplottype/export', '_blank');
  ElMessage.success('导出任务已开始');
};

const handleViewDetails = (row: any) => {
  ElMessage.info(`查看户型详情: ${row.name}`);
  console.log('户型详情:', row);
};



const handleDialogClose = () => {
  dialogVisible.value = false;
  resetForm();
};

const handleSubmit = async () => {
  if (!formRef.value) return;

  try {
    await formRef.value.validate();

    submitLoading.value = true;

    // 设置buildingId为当前楼栋ID
    (formData as any).buildingId = buildingId.value;

    let success = false;
    if (isEdit.value) {
      success = await updateType(formData);
    } else {
      success = await saveType(formData);
    }

    if (success) {
      dialogVisible.value = false;
      resetForm();
      getTypeList();
    }
  } catch (error) {
    console.error('表单验证失败:', error);
  } finally {
    submitLoading.value = false;
  }
};

// 初始化
onMounted(() => {
  if (!buildingId.value) {
    ElMessage.error('缺少楼栋ID参数');
    return;
  }
  getTypeList();
});
</script>

<style scoped>
.type-container {
  display: flex;
  flex-direction: column;
}

.person-container {
  max-width: 1290px;
  width: 100%;
  margin: 20px auto;
  display: flex;
  justify-content: flex-start;
  align-items: flex-start;
  box-sizing: border-box;
  padding: 0 16px;
}

.type-content {
  margin-left: 10px;
  flex: 1 1 0;
  min-width: 0;
  width: 100%;
  max-width: 100%;
}

.type-header {
  margin-bottom: 16px;
  display: flex;
  gap: 12px;
}

.type-search {
  margin-bottom: 16px;
  display: flex;
  align-items: center;
  gap: 12px;
  flex-wrap: wrap;
}

.table-pagination {
  margin: 16px 0 0 0;
  display: flex;
  justify-content: flex-end;
}

:deep(.center-header) {
  text-align: center !important;
}

:deep(.el-card) {
  min-height: 831px;
}

:deep(.el-table th) {
  background: #f5f7fa !important;
}

:deep(.el-table .el-table__cell) {
  padding: 8px 0;
}

.no-data {
  color: #999;
  font-style: italic;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}



:deep(.el-dialog__body) {
  padding: 20px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-input-number) {
  width: 100%;
}

@media (max-width: 900px) {
  .person-container {
    flex-direction: column;
    align-items: stretch;
    padding: 0 4px;
  }

  .type-content {
    margin-left: 0;
    width: 100%;
    max-width: 100%;
  }

  .type-header {
    flex-direction: column;
    gap: 8px;
  }

  .type-search {
    flex-direction: column;
    align-items: stretch;
    gap: 8px;
  }

  .type-search .el-input,
  .type-search .el-select {
    width: 100% !important;
  }

  :deep(.el-dialog) {
    width: 95% !important;
    margin: 0 auto;
  }

  :deep(.el-table .el-table__cell) {
    padding: 4px 0;
  }
}
</style>
